package me.xuym.crawler.lrts;

import com.cbs.java.component.application.Application;
import com.cbs.java.component.application.BaseArgs;
import com.cbs.java.component.network.HttpClient;
import com.cbs.java.component.network.Request;
import com.cbs.java.component.network.Response;
import com.cbs.java.component.network.decoder.TextDecoder;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import me.xuym.crawler.Processor;
import me.xuym.crawler.Task;
import me.xuym.crawler.simpleextension.dispatcher.SimpleDebugDispatcher;
import me.xuym.crawler.simpleextension.dispatcher.SimpleDebugDispatcherInput;
import me.xuym.crawler.simpleextension.dispatcher.SimpleEmailDispatcher;
import me.xuym.crawler.simpleextension.dispatcher.SimpleEmailDispatcherInput;

import java.security.MessageDigest;
import java.util.List;

/**
 * Created by broche on 02/01/2018.
 */
public class MyApplication extends Application {
    private BaseArgs baseArgs = new BaseArgs();

    public MyApplication(String[] args) {
        super(args);
    }

    @Override
    public boolean isDebug() {
        return false;
    }

    @Override
    public String applicationName() {
        return "crawler/lrts";
    }

    @Override
    public BaseArgs getArgs() {
        return baseArgs;
    }

    @Override
    public void start() {
        super.start();
        try {
            String host = "116.211.168.177";
            String uri = "/yyting/integral/taskEvent.action";
            // sorted params
            String params = "?imei=%s&nwt=1&q=21247&reqId=%s&taskId=6&token=%s";
            // sorted finalparams
            String finalparams = "?imei=%s&nwt=1&q=21247&reqId=%s&sc=%s&taskId=6&token=%s";

            String imei = getConfigs().getProperty("IMEI", "");
            String token = getConfigs().getProperty("Token", "");
            String timestamp = System.currentTimeMillis() + "";
            String digest = digest(uri + String.format(params, imei, timestamp, token));

            // email config
            String e_account = getConfigs().getProperty("SimpleEmailDispatcher.Account", "");
            String e_password = getConfigs().getProperty("SimpleEmailDispatcher.Password", "");
            String e_host = getConfigs().getProperty("SimpleEmailDispatcher.Host", "");
            String e_emailsstr = getConfigs().getProperty("SimpleEmailDispatcher.Emails", "[]");
            List<String> e_emails = new Gson().fromJson(e_emailsstr, new TypeToken<List<String>>() {
            }.getType());

            String finalUrl = "http://" + host + uri + String.format(finalparams, imei, timestamp, digest, token);
            Task task = new Task(this);
            task.process(new MyProcessor(this, finalUrl))
                    .process(new SimpleDebugDispatcher(this))
                    .process(new SimpleEmailDispatcher(this, e_emails, e_account, e_password, e_host, "【懒人听书】签到"));


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String digest(String str) {
        String key = "iJ0DgxmdC83#I&j@iwg";
        str = str + key;
        StringBuilder stringBuilder = new StringBuilder();
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(str.getBytes("UTF-8"));
            byte[] bresult = digest.digest();
            for (int i = 0; i < bresult.length; i++) {
                String tmp = Integer.toHexString(bresult[i] & 0xFF);
                if (tmp.length() == 1) {
                    tmp = "0" + tmp;
                }
                stringBuilder.append(tmp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }

    static class MyEntity implements SimpleDebugDispatcherInput, SimpleEmailDispatcherInput {
        private String content;

        public MyEntity(String content) {
            this.content = content;
        }

        @Override
        public String simpleDebugDispatcherContent() {
            return content;
        }

        @Override
        public String simpleEmailDispatcherContent() {
            return content;
        }
    }

    static class MyProcessor extends Processor<String, MyEntity> {
        private String url;

        public MyProcessor(Application application, String url) {
            super(application);
            this.url = url;
        }

        @Override
        protected MyEntity onProcess(String content) throws Exception {
            HttpClient.Builder builder = new HttpClient.Builder();
            HttpClient httpClient = builder.build();

            Request request = new Request(url)
                    .header("User-Agent", "Android6.0.1/yyting/LeMobile/LEX720/ch_qq_appcenter/151/Android")
                    .header("Accept-Encoding", "gzip,deflate,sdch")
                    .header("ClientVersion", "ClientVersion: 6.2.0")
                    .header("Referer", "yytingting.com")
                    .header("Host", "dapi.mting.info")
                    .header("Connection", "Keep-Alive")
                    .setDecoder(new TextDecoder());
            Response response = httpClient.sendSync(request);
            String result = response.getResult().toString();
            return new MyEntity(result);
        }
    }

    public static void main(String[] args) {
        MyApplication myApplication = new MyApplication(args);
        myApplication.start();
    }
}
